<template>
    <div class="assignment_modal">

        <up-modal :show="showModal" :closeOnClickOverlay='true' @close="showModal = false">
            <template #default>
                <up-icon name="close" class="icon_close" @click="closeModal" style="z-index: 9999;"></up-icon>

                <h5 class="modal_tit"> 业绩分配</h5>
                <div class="content" id="scrollContainer">
                    <div class="item">
                        <div class="item_tit">产品名称</div>
                        <div class="tit">{{ productName }}</div>

                    </div>
                    <div class="item">
                        <div class="item_tit_none">订单金额</div>
                        <div class="tit" style="color: #ff6a00;">{{ amount }}</div>

                    </div>
                    <div class="item">
                        <div class="item_tit_none">订单业绩</div>
                        <div class="tit" style="color: #ff6a00;">{{ achievement }}</div>

                    </div>
                    <div class="item" v-if="isAllot == '1'">

                        <div class="item_tit_none">退费金额</div>
                        <div class="tit" style="color: #ff6a00;">{{ retAmount }}</div>

                    </div>
                    <div class="item" v-if="isAllot == '1'">
                        <div class="item_tit_none">退还业绩</div>
                        <div class="tit" style="color: #ff6a00;">{{ retAchievement }}</div>

                    </div>
                    <div class="scroll">
                        <div style="background-color: rgba(64,149,229,0.11);padding: 10rpx 0;margin-top: 10rpx;border-radius:5px"
                            v-for="item, index in userList" v-show="userList.length">
                            <div class="item">
                                <div class="item_tit">分配员工</div>
                                <div class="item_select" @tap="showPicker = true; Userindex = index">
                                    <span>{{ item.name ? item.name : '请选择' }}</span> <up-icon
                                        name="arrow-right"></up-icon>
                                </div>
                            </div>
                            <div class="item">
                                <div class="item_tit">分配业绩</div>
                                <div style="" class="item_select"> <up-input placeholder="请输入内容" border="none"
                                        v-model="item.achievement" @change="changeInput"></up-input> </div><image
                                    src="/static/images/mb-trash-can 1@1x.png" alt=""
                                    style="margin-left: 20rpx; cursor: pointer;width: 20px;
height: 20px;" @tap="deleteUser(index)" />
                            </div>

                        </div>
                    </div>

                </div>
                <up-picker :show="showPicker" @confirm="confirmPicker" @close="closePicker" :closeOnClickOverlay="true"
                    v-model="selected" :columns="columns" keyName="name" valueName="id" @cancel='showPicker = false'
                    @change="handleChange"></up-picker>



            </template>

            <template #confirmButton>
                <div class="btn_box">
                    <div class="btn1" @click="addUser">添加员工</div>
                    <div class="btn2" @tap="Endconfirm">确认</div>

                </div>
            </template>
        </up-modal>
    </div>
</template>


<script setup>
import { ref, onMounted, reactive } from 'vue'
import emitter from '../../../utils/eventBus';
import { getBranchUserList, addAchievement, addAchievementList } from '../../../utils/performance';
const showModal = ref(false)
const showPicker = ref(false);
const columns = reactive([]);
const selected = ref([]);
const retAchievement = ref('')
const retAmount = ref()
const Userindex = ref(0)
const isAllot = ref('1')
const closeModal = () => {
    console.log('closeModal called');
    showModal.value = false;
}
const handleChange = (e) => {
    console.log(e)
}
const userList = ref([])
const originalUserList = ref([])
const orderId = ref('')
const productName = ref('')
const amount = ref('')
const achievement = ref('')
const isfenpei = ref('')
emitter.on('openModal', async (item) => {
    columns.length = 0
    showModal.value = true;
    console.log(item)
    orderId.value = item.orderId
    productName.value = item.productName
    amount.value = item.amount
    retAmount.value = item.retAmount
    retAchievement.value = item.retAchievement
    isAllot.value = item.isReturns
    achievement.value = item.achievement
    isfenpei.value = item.isAllot
    // 保存原始数据到originalUserList
    originalUserList.value = item.data ? [...item.data] : [{
        name: '',
        achievement: '',
        userId: ''
    }]
    // 初始加载时从originalUserList复制数据
    userList.value = [...originalUserList.value]
    try {
        const res = await getBranchUserList({ orderId: orderId.value })   //JSON.parse(localStorage.getItem('userinfo')).businessId
        console.log(res)
        if (columns.length == 0) {
            columns.push(res.data)
        } else {

        }
    } catch (e) {
        console.log(e)
    }

});
const closePicker = () => {
    showPicker.value = false
}
const confirmPicker = (e) => {
    userList.value[Userindex.value] = e.value[0]
    showPicker.value = false
}

const addUser = () => {
    userList.value.push({
        name: '',
        achievement: '',
        userId: ''
    })
}
const Endconfirm = async () => {



    if (userList.value.length == 0) {
        uni.showToast({
            title: '请重新分配',
            icon: 'none',
            duration: 2000
        });
        return
    }

    // 检查是否存在相同名称的员工
    const nameSet = new Set();
    for (const user of userList.value) {
        if (user.name) {
            if (nameSet.has(user.name)) {
                uni.showToast({
                    title: '存在重复员工名称，请检查',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            nameSet.add(user.name);
        }
    }
    if (isfenpei.value == '1') {
        try {
            const res = await addAchievementList({
                orderId: orderId.value,
                vo: userList.value
            })
            console.log(res)
            if (res.code == 200) {
                uni.showToast({
                    title: '分配成功',
                    icon: 'success',
                    duration: 2000
                })
                showModal.value = false
                emitter.emit('reloadData')
            }
        } catch (e) {


        }
    } else {
        try {
            const res = await addAchievement({
                orderId: orderId.value,
                vo: userList.value
            })
            console.log(res)
            if (res.code == 200) {
                uni.showToast({
                    title: '分配成功',
                    icon: 'success',
                    duration: 2000
                })
                showModal.value = false
                emitter.emit('reloadData')
            }
        } catch (e) {


        }
    }





}

const deleteUser = (index) => {
    // 假删除：仅从当前显示列表中移除，但保留在原始数据中
    userList.value.splice(index, 1);
    uni.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000
    });
}

// 关闭模态框时不做任何操作，保持原始数据不变
// 重新打开时会从originalUserList加载数据
const changeInput = (e) => {
    console.log(e)
}
</script>


<style lang="scss">
.icon_close {
    font-size: 60rpx;
    position: absolute;
    top: 24rpx;
    right: 24rpx;
}

.modal_tit {
    position: absolute;
    top: 38rpx;

    width: 100%;
    display: flex;
    justify-content: center;
    color: rgb(16, 16, 16);
    font-size: 32rpx;
    text-align: left;
    font-family: SourceHanSansSC-bold;
}

.assignment_modal {
    .content {
        width: 100%;
        margin-top: 40rpx;
        text-align: left;

        .scroll {
            height: 900rpx;
            overflow: scroll;
            z-index: 9999 !important;
        }

        .item {
            display: flex;
            align-items: center;
            margin-top: 10rpx;

            .icon_item {
                position: absolute;
                bottom: 0;
                right: 0;
            }

            .item_tit {
                position: relative;
                color: rgba(79, 79, 79, 1);
                font-size: 28rpx;
                text-align: left;
                font-family: PingFangSC-regular;
                padding-left: 24rpx;
            }

            .item_tit_none {
                position: relative;
                color: rgba(79, 79, 79, 1);
                font-size: 28rpx;
                text-align: left;
                font-family: PingFangSC-regular;
                padding-left: 24rpx;

            }

            .item_tit::before {
                content: '*';
                position: absolute;
                left: 8rpx;
                top: 66%;
                transform: translateY(-50%);
                color: #FF4D4F;
                font-size: 28rpx;
            }

            .tit {
                flex: 1;
                margin-left: 20rpx;
                color: rgba(79, 79, 79, 1);
                font-size: 28rpx;
                text-align: left;
                font-family: SourceHanSansSC-regular;
            }

            .item_select {
                width: 222rpx;
                height: 56rpx;
                line-height: 56rpx;
                border-radius: 8rpx;
                background-color: rgba(255, 255, 255, 1);
                color: rgba(16, 16, 16, 1);
                font-size: 28rpx;
                font-family: -regular;
                margin-left: 20rpx;
                padding: 0 10rpx;
                display: flex;
                justify-content: space-between;
                align-items: center;

            }

        }

    }


}

.btn_box {
    width: 100%;
    display: flex;
    justify-content: right;

    .btn1 {
        width: 75px;
        height: 33px;
        line-height: 33px;
        border-radius: 4px;
        background-color: rgba(64, 149, 229, 0.17);
        color: rgba(64, 149, 229, 1);
        font-size: 14px;
        text-align: center;
        font-family: -regular;
        border: 1px solid rgba(64, 149, 229, 1);
        margin-right: 15rpx;
    }

    .btn2 {
        width: 75px;
        height: 35px;
        line-height: 33px;
        border-radius: 4px;
        background-color: rgba(78, 122, 255, 1);
        color: rgba(255, 255, 255, 1);
        font-size: 14px;
        text-align: center;
        font-family: -regular;
    }
}
</style>